package com.Fen.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.Fen.constant.MessageConstant;
import com.Fen.constant.StatusConstant;
import com.Fen.dto.DishDTO;
import com.Fen.dto.DishPageQueryDTO;
import com.Fen.entity.Dish;
import com.Fen.entity.DishFlavor;
import com.Fen.entity.Setmeal;
import com.Fen.exception.DeletionNotAllowedException;
import com.Fen.mapper.DishFlavorMapper;
import com.Fen.mapper.DishMapper;
import com.Fen.mapper.SetmealDishMapper;
import com.Fen.mapper.SetmealMapper;
import com.Fen.result.PageResult;
import com.Fen.service.DishService;
import com.Fen.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.insert(dish);
        //获取菜品id
       Long dishId=dish.getId();

       List<DishFlavor> flavors= dishDTO.getFlavors();
       if(flavors!=null && !flavors.isEmpty()){
           for(DishFlavor flavor:flavors){
               flavor.setDishId(dishId);
           }
           dishFlavorMapper.insertBatch(flavors);
       }
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page=dishMapper.pageQuery(dishPageQueryDTO);
        long total= page.getTotal();
        List<DishVO> list=page.getResult();
        return new PageResult(total,list);
    }

    @Override
    //涉及多个数据表操作，要使用该注解，使数据表都可以进行操作
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //判断产品能否删除（启售中）
        for (Long id:ids){
            Dish dish=dishMapper.selectById(id);
            if(dish.getStatus()== StatusConstant.ENABLE){
                throw  new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断产品能否删除（套餐关联的）
        List<Long> longs= setmealDishMapper.getSetmealDishIds(ids);
        if(longs!=null && !longs.isEmpty()){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品
        for (Long id:ids){
            dishMapper.deleteById(id);
            //删除菜品关联的口味数据
            dishFlavorMapper.deleteByDishId(id);
        }
    }

    @Override
    public DishVO getByIdWithFlavor(Long id) {
      Dish dish=dishMapper.selectById(id);

      List<DishFlavor> flavors=dishFlavorMapper.selectByDishId(id);

      DishVO dishVO=new DishVO();
      BeanUtils.copyProperties(dish,dishVO);
      dishVO.setFlavors(flavors);

      return dishVO;
    }

    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        //修改菜品的基本信息
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.updateById(dish);
        //删除菜品口味信息
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //修改菜品口味信息
        List<DishFlavor> flavors=dishDTO.getFlavors();
        if(flavors!=null && !flavors.isEmpty()){
            for(DishFlavor flavor:flavors){
                flavor.setDishId(dishDTO.getId());
            }
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品起售停售
     *
     * @param status
     * @param id
     */
    @Transactional
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.updateById(dish);

        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setmealDishMapper.getSetmealDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
